package com.exp2.caloriedaily.service

import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.util.Log
import com.exp2.caloriedaily.domain.CalorieData
import org.jetbrains.anko.db.ManagedSQLiteOpenHelper
import java.time.chrono.ThaiBuddhistChronology
import java.util.*
import kotlin.math.log


class CalorieService (var context: Context):ManagedSQLiteOpenHelper(context,"calorie.db",null){

    companion object{
        var DB_NAME:String="calorie.db"

        var TABLE_NAME="calorie_info"

        private var instance: CalorieService?=null

        @Synchronized
        fun getInstance(ctx:Context):CalorieService{
            if (instance==null){
                instance= CalorieService(ctx.applicationContext)
            }
            return instance !!
        }
    }


    override fun onCreate(db: SQLiteDatabase?) {
        val drop_sql="DROP TABLE IF EXISTS $TABLE_NAME;"
        db?.execSQL(drop_sql)
        val create_sql="CREATE TABLE IF NOT EXISTS $TABLE_NAME("+
                "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"+
                "date DATE NOT NULL," + "calorie INT NOT NULL);"
        db?.execSQL(create_sql)
    }

    override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {

    }

    //删除数据
    fun delete(condition:String):Int{
        var count=0
        use {
            count=delete(TABLE_NAME,condition,null)
        }
        return count
    }

    //添加数据
    fun insert(info:CalorieData):Long{
        var result:Long=-1
        var  tempArray:List<CalorieData>
        if (info.date!=null){
            val condition ="date = '${info.date}'"
            tempArray=query(condition)
            Log.d("query result is",tempArray.toString())
            if (tempArray.isNotEmpty()){
                result= tempArray[0].id!!
                Log.d("update","update id is $result")
                info.id=result
                update(info,condition)
                return result
            }
        }

        val cv = ContentValues()
        cv.put("date",info.date)
        cv.put("calorie",info.calorie)
        use {
            result=insert(TABLE_NAME,"",cv)
        }
        return result
    }

    //更新数据
    @JvmOverloads
    fun update(info: CalorieData,condition: String="id=${info.id}"):Int{
        val cv = ContentValues()
        cv.put("date",info.date)
        cv.put("calorie",info.calorie)
        var count=0
        use {
            count=update(TABLE_NAME,cv,condition,null)
        }
        return count
    }


    //查询数据
    fun query(condition: String):List<CalorieData>{
        val sql= "select id,date,calorie from $TABLE_NAME where $condition order by date asc;"
        Log.d("sql is",sql)
        var infoArray= mutableListOf<CalorieData>()
        use {
            val cursor = rawQuery(sql,null)
            if (cursor.moveToFirst()){
                while (true){
                    val info=CalorieData()
                    info.id=cursor.getLong(0)
                    info.date=cursor.getString(1)
                    info.calorie=cursor.getInt(2)
                    infoArray.add(info)
                    if (cursor.isLast){
                        break;
                    }
                    cursor.moveToNext()
                }
            }
            cursor.close()
        }
        return infoArray
    }

    fun deleteAll():Int=delete("1=1")
    fun queryAll():List<CalorieData> =query("1=1")

}